package database_interaction;

import java.sql.*;
import java.util.InputMismatchException;

/**
 * @file Database.java
 * @version 0.1
 * @author James Dibble 10009689
 */
public class Database {
    // <editor-fold defaultstate="collapsed" desc="Attributes">
    private String _serverURL;
    private Connection _sqlConnection;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Constructors">
    public Database(String serverURL) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        this._serverURL = serverURL;
        Class.forName ("com.mysql.jdbc.Driver").newInstance();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Methods">
    /**
     * Connect a database using the given parameters.
     * 
     * @param strUser
     * @param strPassword
     * @throws SQLException 
     */
    public void connect(String strUser, String strPassword) throws SQLException{
        _sqlConnection = DriverManager.getConnection(_serverURL, strUser, strPassword);
    }
    
    public void executeQuery(String strQuery) throws SQLException{
        Statement thisStatement = _sqlConnection.createStatement();
        thisStatement.execute(strQuery);
    }
    
    public void executeQuery(SQLQuery query) throws SQLException, JDBCException{
        Statement thisStatement = _sqlConnection.createStatement();
        switch(query.getQueryType()){
            case SELECT:
              thisStatement.execute(query.getQueryString());
                break;
            case UPDATE:
              thisStatement.executeUpdate(query.getQueryString());
                break;
            case INSERT:
              thisStatement.execute(query.getQueryString());
                break;
            case DELETE:
              thisStatement.execute(query.getQueryString());
              break;
            default:
                throw new JDBCException("Unknow Query type used.");
        }
    }
    
    public ResultSet executeQuery(SelectQuery query) throws SQLException, JDBCException{
        Statement thisStatement = _sqlConnection.createStatement();
        return thisStatement.executeQuery(query.getQueryString());
    }
    // </editor-fold>
}
